#include <project.h>
#include "userMain.h"
#include "userUartTxCtrl.h"

circle_buffer userTxBuffer;
unsigned char userUartTxResetFlag = 0;
void userTxBufferPop(unsigned char* user_buf)
{
    *user_buf = userTxBuffer.circle_buffer[userTxBuffer.read_pos];    //如果缓冲区非空则取头节点值并偏移头节点
    if(++userTxBuffer.read_pos >= BUFFER_TX_MAX)
         userTxBuffer.read_pos = 0;
}

void userGetTxBufferLen(unsigned char* user_TxLen)
{
    if(userUartTxResetFlag) 
    {
        *user_TxLen = 0;
        return ;
    }
    if(userTxBuffer.write_pos >= userTxBuffer.read_pos)
    {
        *user_TxLen = userTxBuffer.write_pos - userTxBuffer.read_pos;
    }
    else 
    {
        *user_TxLen = BUFFER_TX_MAX - userTxBuffer.read_pos + userTxBuffer.write_pos;
    }
}

void userTxBufferPush(const unsigned char _buf)
{   
    if(userUartTxResetFlag)   userTxBufferReset();
    userTxBuffer.circle_buffer[userTxBuffer.write_pos]=_buf; //从尾部追加
    if(++userTxBuffer.write_pos>=BUFFER_TX_MAX)           //尾节点偏移
        userTxBuffer.write_pos=0;                      //大于数组最大长度 制零 形成环形队列
}

void userTxBufferPushFrame(unsigned char* src_buf, unsigned char len)
{
    unsigned char user_i;
    if(len==0) return ;
    for(user_i=0;user_i<len;user_i++)
    {
        userTxBufferPush(*(src_buf+user_i));
    }
    _NOP;
}

void userGetTxFrameData(unsigned char* dst_buf, unsigned char len)
{
    unsigned char user_i;
    if(len==0) return ;
    for(user_i=1;user_i<len;user_i++)
    {
        userTxBufferPop(dst_buf+user_i);
    }
    if(userTxBuffer.read_pos >= userTxBuffer.write_pos)
    {
       userUartTxResetFlag = 1;
    }
}
void userTxBufferReset(void)
{
    userUartTxResetFlag = 0;
    userTxBuffer.read_pos=0;
    userTxBuffer.write_pos=0;
}
#define     UART_TX_IDLE    10
unsigned char uUartTxFinishMarkTick = 0;
void userUartTxFinishTick(void)
{
    if(uUartTxFinishMarkTick < 240)
     uUartTxFinishMarkTick++;
}

unsigned char userUartTxIdle(void)
{
    if(uUartTxFinishMarkTick < UART_TX_IDLE) 
        return 0;
    else
        return 1;
}
